import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

class HttpStudy extends StatefulWidget {
  const HttpStudy({super.key});

  @override
  State<HttpStudy> createState() => _HttpStudyState();
}

class _HttpStudyState extends State<HttpStudy> {
  var getRes = '';
  var postRes = '';
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('演示Http网络请求')),
      body: Column(children: [
        _doGetBtn(),
        Text('get响应：$getRes'),
        _doPostBtn(),
        Text('post响应：$postRes'),
      ],),
    );
  }

  //#region 测试 get 方法
  _doGetBtn(){
    return ElevatedButton(onPressed: _doGet, child: const Text('发送GET请求'));
  }
  _doGet() async {
    print('_doGet');
    var uri = Uri.parse('https://showawx.xdfznh.club/visitorbe/test/now');
    var res = await http.get(uri);
    print('请求得到的响应：${res.toString()}');
    if(res.statusCode == 200){
      // res.body 是开发人员后台响应的数据
      print('请求成功,body:${res.body}');
      setState(() {
        getRes = res.body;
      });

      // json 数据反序列化
      var data = jsonDecode(res.body);
      print('data:${data}');

      var success = data['success'];
      var msg = data['msg'];
      print('success:$success,msg:$msg');
    }else{
      setState(() {
        getRes = '请求失败，code:${res.statusCode},body:${res.body}';
      });
    }
  }
  //#endregion

  //#region 测试 post 方法
  _doPostBtn(){
    return ElevatedButton(onPressed: _doPost, child: const Text('发送POST请求'));
  }
  _doPost() async {
    var uri = Uri.parse('https://www.xdfznh.club/wxpadbe/dev/proxyUrl');
    var params = {'rawUrl':'https://www.xdfznh.club'};
    var res = await http.post(
        uri,
        body: jsonEncode(params),
        headers: {
          'Content-Type': 'application/json; charset=UTF-8', // 关键：设置 Content-Type
        },
    );
    if(res.statusCode == 200){
      print('请求来的响应：${res.body}');
      setState(() {
        postRes = res.body;
      });
    }else{
      setState(() {
        postRes = 'post请求异常，code:${res.statusCode},msg:${res.body}';
      });
    }
  }
  //#endregion
}
